package com.lj.frame.file.service.impl;

import com.lj.commons.exception.YerException;
import com.lj.frame.file.entity.FileConf;
import com.lj.frame.file.entity.LocalFile;
import com.lj.frame.file.entity.ObsFile;
import com.lj.frame.file.entity.UploadFile;
import com.lj.frame.file.repo.FileConfRepository;
import com.lj.frame.file.repo.UploadFileRepository;
import com.lj.frame.file.service.FileService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;

@RequiredArgsConstructor
@Slf4j
@Service
public class FileServiceImpl implements FileService {

    private final UploadFileRepository uploadFileRepository;
    private final FileConfRepository fileConfRepository;

    @Override
    public UploadFile findByMd5(String md5) {
        return uploadFileRepository.getBaseMapper().findByMd5(md5);
    }

    @Override
    public UploadFile findByPath(String path) {
        return uploadFileRepository.getById(path);
    }

    @Override
    public void upload(UploadFile uploadFile, InputStream inputStream) throws YerException {
        upload(uploadFile, inputStream, "application/octet-stream");
    }


    @Override
    public void upload(UploadFile uploadFile, InputStream inputStream, String contentType) throws YerException {
        FileConf fileConf = fileConfRepository.getActive();
        if (Objects.isNull(fileConf)){
            throw new YerException("没有可用文件配置");
        }
        String path = getPath(uploadFile.getName());
        uploadFile.setPath(path);
        try{
            switch (fileConf.getType()){
                case "local":
                    LocalFile.putObject(fileConf.getBucketName(), uploadFile.getPath(), inputStream);
                    break;
                default:
                    ObsFile.build(fileConf)
                            .putObject(fileConf.getBucketName(), uploadFile.getPath(), contentType, inputStream);
                    break;
            }
            //存储到数据库
            uploadFileRepository.save(uploadFile);
        }catch (Exception e){
            throw new YerException("上传失败"+e.getMessage());
        }
    }

    private String getPath(String name){
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        return String.format("/%s/%s", format.format(new Date()), name);
    }
}
